<template>
  <a-spin tip="Loading..." :spinning="spinning">
    <a-form :form="form" @submit="handleSubmit">
      <div class="operation-box">
        <a-card title="基本信息">
          <a-row class="basic-info">
            <a-col v-bind="col">
              <a-form-item label="姓名" v-bind="formItemCol">
                <a-input placeholder="请输入姓名"
                         v-decorator="['name',{rules:[{required:true,message:'姓名不可为空'}],initialValue:''}]"/>
              </a-form-item>
            </a-col>
            <a-col v-bind="col">
              <a-form-item label="性别" v-bind="formItemCol">
                <a-radio-group :options="[{label:'男',value:1},{label:'女',value:2},{label:'其它',value:3}]"
                               v-decorator="['gender',{rules:[{required:true,message:'性别不可为空'}],initialValue:1}]"/>
              </a-form-item>
            </a-col>
            <a-col v-bind="col">
              <a-form-item label="手机号" v-bind="formItemCol">
                <a-input placeholder="请输入手机号"
                         v-decorator="['phone',{rules:[{required:true,message:'手机号不可为空'},{pattern:/^1[3456789]\d{9}$/,message:'请输入正确的手机号'}],initialValue:''}]"/>
              </a-form-item>
            </a-col>
            <a-col v-bind="col">
              <a-form-item label="出生日期" v-bind="formItemCol">
                <a-date-picker :style="{width:'100%'}" placeholder="请选择出生日期" v-decorator="['createtime']"/>
              </a-form-item>
            </a-col>
            <a-col v-bind="col">
              <a-form-item label="单位名称" v-bind="formItemCol">
                <a-input placeholder="请输入单位名称" v-decorator="['work_area',{initialValue:''}]"/>
              </a-form-item>
            </a-col>
            <a-col v-bind="col">
              <a-form-item label="照 片 " v-bind="formItemCol" extra="最多可上传1张图片，且图片大小不可超过2M。">
                <a-upload name="file" accept="image/*" :action="baseURL + 'community/uploadPic?token=' + token" @preview="imgPreview" v-decorator="['imgs',{initialValue:[],valuePropName:'fileList',getValueFromEvent:imageUpload}]">
                  <a-button> <a-icon type="upload" /> 上传图片 </a-button>
                </a-upload>
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>
      </div>
      <div class="operation-box">
        <a-card title="联系信息">
          <a-row>
            <a-col v-bind="col">
              <a-form-item label="QQ号" v-bind="formItemCol">
                <a-input placeholder="请输入QQ号"
                         v-decorator="['qq',{initialValue:''}]"/>
              </a-form-item>
            </a-col>
            <a-col v-bind="col">
              <a-form-item label="微信号" v-bind="formItemCol">
                <a-input placeholder="请输入微信号"
                         v-decorator="['wechat',{initialValue:''}]"/>
              </a-form-item>
            </a-col>
            <a-col v-bind="col">
              <a-form-item label="电子邮箱" v-bind="formItemCol">
                <a-input placeholder="请输入电子邮箱"
                         v-decorator="['email',{initialValue:''}]"/>
              </a-form-item>
            </a-col>
            <a-col v-bind="col">
              <a-form-item label="紧急联系人" v-bind="formItemCol">
                <a-input placeholder="请输入紧急联系人"
                         v-decorator="['sos_user',{initialValue:''}]"/>
              </a-form-item>
            </a-col>
            <a-col v-bind="col">
              <a-form-item label="请输紧急联系人电话" v-bind="formItemCol">
                <a-input placeholder="请输紧急联系人电话" v-decorator="['sos_call',{initialValue:''}]"/>
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>
      </div>
      <div class="operation-box">
        <a-card title="其它信息">
          <a-row>
            <a-col v-bind="col">
              <a-form-item label="民 族 " v-bind="formItemCol">
                <a-select placeholder="请选择民族" :options="famous" v-decorator="['race',{initialValue:0}]" />
              </a-form-item>
            </a-col>
            <a-col v-bind="col">
              <a-form-item label="政治面貌" v-bind="formItemCol">
                <a-input placeholder="请输入政治面貌" v-decorator="['po_status',{initialValue:''}]"/>
              </a-form-item>
            </a-col>
            <a-col v-bind="col">
              <a-form-item label="婚姻状况" v-bind="formItemCol">
                <a-select placeholder="请选择婚姻状况" :options="[{value:'0',label:'未婚'},{value:'1',label:'已婚'}]" v-decorator="['marriage']"/>
              </a-form-item>
            </a-col>
            <a-col v-bind="col">
              <a-form-item label="身份证号" v-bind="formItemCol">
                <a-input placeholder="请输入身份证号" v-decorator="['license',{rules:[{validator:isIdCard}],initialValue:''}]"/>
              </a-form-item>
            </a-col>
            <a-col v-bind="col" style="height:102px;">
              <a-form-item label="身份证照片" v-bind="formItemCol" extra="最多可上传1张图片，且图片大小不可超过2M。">
                <a-upload name="file" accept="image/*" :action="baseURL + 'community/uploadPic?token=' + token" @preview="imgPreview" v-decorator="['license_img',{initialValue:[],valuePropName:'fileList',getValueFromEvent:imageUpload}]">
                  <a-button> <a-icon type="upload" /> 上传图片 </a-button>
                </a-upload>
              </a-form-item>
            </a-col>
            <a-col v-bind="col">
              <a-form-item label="户口类型" v-bind="formItemCol">
                <a-select :options="[{ label: '城镇户口', value: 1 },{ label: '农村居民户口', value: 2 },{ label: '集体户口', value: 3 }]" placeholder="请选择户口类型" v-decorator="['account_type',{initialValue:undefined}]"/>
              </a-form-item>
            </a-col>
            <!-- <a-col v-bind="col">
              <a-form-item label="户籍地址" v-bind="formItemCol">
                <a-cascader :options="city" placeholder="请选择户籍地址" v-decorator="['account_address',{initialValue:undefined}]" />
              </a-form-item>
            </a-col> -->
            <a-col v-bind="col">
              <a-form-item label="户籍地址" v-bind="formItemCol">
                <a-input placeholder="请输入详细户籍地址" v-decorator="['address',{initialValue:''}]"/>
              </a-form-item>
            </a-col>
<!--            <a-col v-bind="col">-->
<!--              <a-form-item label="暂住证号码" v-bind="formItemCol">-->
<!--                <a-input placeholder="请输入暂住证号码" v-decorator="['tem_permit',{initialValue:''}]"/>-->
<!--              </a-form-item>-->
<!--            </a-col>-->
<!--            <a-col v-bind="col">-->
<!--              <a-form-item label="居住类型" v-bind="formItemCol">-->
<!--                <a-select :options="[{ label: '常住', value: 1 },{ label: '暂住', value: 2 },{ label: '其它', value: 3 }]" placeholder="请选择居住类型" v-decorator="['tem_type',{initialValue:undefined}]"/>-->
<!--              </a-form-item>-->
<!--            </a-col>-->
            <a-col v-bind="col">
              <a-form-item label="备 注 " v-bind="formItemCol">
                <a-input placeholder="请输入备注" v-decorator="['remarks',{initialValue:''}]"/>
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>
      </div>
      <a-form-item style="display: none;">
        <a-input type="hidden" v-decorator="['status',{initialValue:4}]"></a-input>
      </a-form-item>
      <a-form-item>
        <div class="toolbar___2Bjan" style="width: 100%; height: 60px;">
          <div class="left___WFbXa"></div>
          <div class="right___1B23o">
            <button type="submit" class="ant-btn ant-btn-primary">保 存</button>
            <button type="button" class="ant-btn" style="margin-left: 16px;" @click="() => { $router.go(-1) }">返 回</button>
          </div>
        </div>
      </a-form-item>
    </a-form>
  </a-spin>
</template>

<script>
  import { ACCESS_TOKEN } from '@/store/mutation-types'
  import { mapState } from 'vuex'
  export default {
    name: 'data_household_nonindex_operation',
    data() {
      return {
        token:this.$ls.get(ACCESS_TOKEN), // 用户token
        imgsFileList: [], // 住户照片
        city: this.$store.state.app.city, // 省市县
        baseURL: this.axios.defaults.baseURL,
        spinning: false,
        form: this.$form.createForm(this),
        col: { xs: { span: 24 }, sm: { span: 24 }, md: { span: 12 }, lg: { span: 8 } },
        formItemCol: { wrapperCol: { span: 20, sm: { span: 22 } } },
        previewImage: '', // 图片预览
        imagePreviewVisible: false,
        id: '', // 住户id
      }
    },
    computed:{
      ...mapState({
        famous:state => state.app.famous
      })
    },
    async mounted() {
      let { id } = this.$route.params;
      this.id = id === 'add' ? 0 : Number(id);
      if(!isNaN(this.id)){
        if(this.id !== 0) {
          let formFiled = this.form.getFieldsValue();
          let data = await this.getInfo(id);
          let setData = {};
          for(let key in formFiled) setData[key] = data[key];
          this.form.setFieldsValue(setData);
        }
      }else this.$router.go(-1);
    },
    methods: {
      // 获取小区设置信息
      getInfo(id) {
        return new Promise((resolve,reject) => {
          this.axios({
            method:'post',
            url:'/household/getInfo',
            params:{id,token:this.token}
          }).then(res => {
            let { code,msg,data:{data} } = res;
            if(code === 0){
              data['marriage'] = this.$common.isEmpty(data['marriage']) ? undefined : data['marriage'];
              data['account_type'] = this.$common.isEmpty(data['account_type']) ? undefined : data['account_type'];
              resolve(data);
            }else this.$message.warning(msg);
          }).catch(err => {
            this.$message.error('服务器发生错误...');
          })
        })
      },
      // 提交信息
      handleSubmit(e) {
        e.preventDefault()
        this.form.validateFields((err, values) => {
          if (err) {
            for (let key in err) {
              for (let item of err[key]['errors']) return this.$message.warning(item['message'], 2)
            }
          }
          Object.assign(values,{token:this.token,id:this.id});
          this.spinning = true;
          this.axios({
            method: 'post',
            url: '/household/operation',
            data: values
          }).then(res => {
            this.spinning = false
            if (res.code == 0) {
              this.$message.success('保存成功', 1)
              this.$router.push({ name: 'data_household_nonindex'})
            } else this.$message.warning(res.msg)
          }).catch(() => {
            this.$message.error('服务器发生错误...', 2), this.spinning = false
          })
        })
      },
      // 上传图片
      imageUpload({file,fileList}) {
        if((file.size / 1024 / 1024) > 2) {
          this.$message.warning('图片最大不可超过2M',2);
          return [];
        }
        if(file.status === 'removed') return [];
        if(file.status === 'uploading') return fileList;
        if(file.status === 'done'){
          let { code,msg,data } = file.response;
          if(code === 0){
            this.$message.success(msg,1);
            return [{uid:data.id,name:data.file_name,url:this.baseURL+'static/uploads/'+data.url}]
          }else {
            this.$message.error(msg,1);
            return [];
          }
        }
        if(file.status === 'error'){
          this.$message.error('上传失败',1);
          return [];
        }
      },
      // 图片预览
      imgPreview(info) {
        this.previewImage = info.url || info.thumbUrl
        this.imagePreviewVisible = true
      },
      isIdCard(rules,code,callback){
        let city = {11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江 ",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北 ",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏 ",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外 "};
        if(!code) callback();
        if(!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)){
          return callback('身份证号格式错误');
        }else if(!city[code.substr(0,2)]){
          return callback('地址编码错误');
        } else{
          //18位身份证需要验证最后一位校验位
          if(code.length == 18){
            code = code.split('');
            //∑(ai×Wi)(mod 11)
            //加权因子
            let factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ];
            //校验位
            let parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ];
            let sum = 0;
            let ai = 0;
            let wi = 0;
            for (let i = 0; i < 17; i++) {
              ai = code[i];
              wi = factor[i];
              sum += ai * wi;
            }
            let last = parity[sum % 11];
            if(parity[sum % 11] != code[17]){
              return callback('校验位错误');
            }
          }
        }
        return callback();
      }
    }
  }
</script>

<style>
  .basic-info .ant-col-lg-8{
    height:104px
  }
</style>
<style lang="less" scoped>
  .operation-box {
    background: #ffffff;
    margin: 25px 25px 0;
  }
  .toolbar___2Bjan {
    position: fixed;
    width: 100%;
    bottom: 0;
    right: 0;
    height: 56px;
    line-height: 56px;
    -webkit-box-shadow: 0 -1px 2px rgba(0, 0, 0, .03);
    box-shadow: 0 -1px 2px rgba(0, 0, 0, .03);
    background: #fff;
    border-top: 1px solid #e8e8e8;
    padding: 0 24px;
    z-index: 9;
    .left___WFbXa {
      float: left;
    }
    .right___1B23o {
      float: right;
    }
  }
  .toolbar___2Bjan:after {
    content: "";
    display: block;
    clear: both;
  }
</style>